const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
}
const formatTime_age = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') 
}
const formatTime_year = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('.') 
}
const formatTime_year_else = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return year
}
const formatTime_month = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [month, day].map(formatNumber).join('.') 
}

const formatTime_order = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute,second].map(formatNumber).join(':')
}
const formatTime_month_else = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return month+"月"+day+"日"
}
function getweekday(date){
  var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
  var week = "周"+weekArray[new Date(date).getDay()];
  return week;
}
const formatTime_time = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [hour, minute].map(formatNumber).join(':')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function time2date(micro_second) {
  var time = {};
  // 总秒数
  var second = Math.floor(micro_second);
  // 天数
  time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2);
  // 小时
  time.hour = PrefixInteger(Math.floor(second / 3600 % 24), 2);
  // 分钟
  time.minute = PrefixInteger(Math.floor(second / 60 % 60), 2);
  // 秒
  time.second = PrefixInteger(Math.floor(second % 60), 2);

  var newtime = '';
  if (time.day > 0) {
    newtime = time.day + '天' + time.hour + ':' + time.minute + ':' + time.second;
  } else {
    if (time.hour != 0) {
      newtime = time.hour + ':' + time.minute + ':' + time.second;
    } else {
      newtime = time.minute + ':' + time.second;
    }
  }
  return newtime;
}
//不足位数前面补0
function PrefixInteger(num, length) {
  return (Array(length).join('0') + num).slice(-length);
}
function insertStr(soure, start, newStr){   
  return soure.slice(0, start) + newStr + soure.slice(start);
}
// 数组合并
function extend(obj1, obj2) {
  for (var i = 0; i < obj2.length; i++) {
    obj1.push(obj2[i]);
  }
  return obj1
}

function convertToChinaNum(num) {
  var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
  var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千','万', '十', '百', '千','亿');//可继续追加更高位转换值
  if(!num || isNaN(num)){
    return "零";
  }
  var english = num.toString().split("")
  var result = "";
  for (var i = 0; i < english.length; i++) {
    var des_i = english.length - 1 - i;//倒序排列设值
    result = arr2[i] + result;
    var arr1_index = english[des_i];
    result = arr1[arr1_index] + result;
  }
  //将【零千、零百】换成【零】 【十零】换成【十】
  result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
  //合并中间多个零为一个零
  result = result.replace(/零+/g, '零');
  //将【零亿】换成【亿】【零万】换成【万】
  result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
  //将【亿万】换成【亿】
  result = result.replace(/亿万/g, '亿');
  //移除末尾的零
  result = result.replace(/零+$/, '')
  //将【零一十】换成【零十】
  //result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
  //将【一十】换成【十】
  result = result.replace(/^一十/g, '十');
  return result;
}
function randomString(len) {
　len = len || 32;
　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
　var maxPos = $chars.length;
　var pwd = '';
　for (var i = 0; i < len; i++) {
　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
　}
　return pwd;
}
function swapArr(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
}
function removeAllSpace(str) {
  return str.replace(/\s+/g, "");
}
function show_success_toast(res){
  wx.hideLoading()
  if(res.data.code!=200){
    // page_show_toast('请求失败,请稍后再试',2000)
  }
}
function show_fail_toast(){
  wx.hideLoading()
  wx.getNetworkType({
    success: function (res) {
      if(res.networkType=='none'){
        page_show_toast('网络正在路上，请检查您的网络',2000)
      }else{
        page_show_toast('请求超时,请稍后再试',2000)
      }
    }
  })
}
function page_show_toast(text,time){
  wx.showToast({
    title: text,
    icon: 'none',
    duration: time
  })
}
const formatTime_com_time = time => {
  var date=new Date(time),now_date=new Date(),time1=new Date().getTime();
  var year = date.getFullYear(),month = date.getMonth() + 1,day = date.getDate(),hour = date.getHours(),minute = date.getMinutes();
  var day1 = now_date.getDate(),hour1 = now_date.getHours(),minute1 = now_date.getMinutes();
  if((time+24*60*60*1000)<time1){
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
  }else{
    var day_time=day1-day,hour_time=hour1-hour,minute_time=minute1-minute;
    if(day_time>0){
      if(hour_time==0){
        return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
      }else{
        return ((24-hour)+hour1)+'小时前'
      }
    }else{
      if(hour_time>0){
        return (hour1-hour)+'小时前'
      }else{
        return (minute_time>0?minute_time:1)+'分钟前'
      }
    }
  }
}
function get_distance(la1, lo1, la2, lo2) {
  var La1 = la1 * Math.PI / 180.0;
  var La2 = la2 * Math.PI / 180.0;
  var La3 = La1 - La2;
  var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  s = s.toFixed(2);
  return s;
}
//
function toDecimal(x) {
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
      rs = s.length;
      s += '.';
  }
  while (s.length <= rs + 2) {
      s += '0';
  }
  return s;
}
//
function toThousands(num) {
  var result = [ ], counter = 0;
  var number=num.split('.');
  num = (number[0] || 0).toString().split('');
  for (var i = num.length - 1; i >= 0; i--) {
      counter++;
      result.unshift(num[i]);
      if (!(counter % 3) && i != 0) { result.unshift(','); }
  }
  return result.join('')+'.'+number[1];
}
// 下载
function downLoadImg(url){
  return new Promise((resolve,reject)=>{
    wx.downloadFile({
      url: url,
      success:function(res){
        resolve(res);
      },
      fail:function(){}
    })
  })
}
// 倒计时时分秒
function time3date(micro_second) {
  var time = {};
  // 总秒数
  var second = Math.floor(micro_second);
  // 天数
  // time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2);
  // 小时
  time.hour = PrefixInteger(Math.floor(second / 3600 % 24)+Math.floor(second / 3600 / 24)*24, 2);
  // 分钟
  time.minute = PrefixInteger(Math.floor(second / 60 % 60), 2);
  // 秒
  time.second = PrefixInteger(Math.floor(second % 60), 2);

  return time;
}
// 倒计时天时分秒
function time4date(micro_second) {
  var time = {};
  // 总秒数
  var second = Math.floor(micro_second);
  // 天数
  time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2);
  // 小时
  time.hour = PrefixInteger(Math.floor(second / 3600 % 24), 2);
  // 分钟
  time.minute = PrefixInteger(Math.floor(second / 60 % 60), 2);
  // 秒
  time.second = PrefixInteger(Math.floor(second % 60), 2);

  return time;
}
function baseRequest(opt) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: opt.url,
      data: opt.data,
      method: opt.method,
      header: {
        'content-type':'application/json;charset=UTF-8'
      },
      success: function(res) {
        if (res.data.code == 200) {
					resolve(res.data);
        } else {
          reject(res)
          page_show_toast(res.data.message,2000)
        }
        if(res.statusCode==404){
          reject(res)
          page_show_toast('网络请求失败,请稍后再试',2000)
        }
      },
      fail: function(err) {
        reject(err)
				wx.getNetworkType({
					success: function (res) {
            console.log(res)
						if(res.networkType=='none'){
							page_show_toast('网络正在路上，请检查您的网络',2000)
						}else{
							page_show_toast('请求超时,请稍后再试',2000)
						}
					}
				})
      }
    })
  })
}
function tokenRequest(opt) {
	let token=wx.getStorageSync("token")?wx.getStorageSync("token"):'';
  return new Promise((resolve, reject) => {
    wx.request({
      url: opt.url,
      data: opt.data,
      method: opt.method,
      header: {
        'content-type':'application/json;charset=UTF-8',
				'x-access-token':token,
				'x-idempotent-token': opts.x_token?opts.x_token:''
      },
      success: function(res) {
        if (res.data.code == 200) {
					resolve(res.data);
        } else {
          reject(res)
          page_show_toast(res.data.message,2000)
        }
        if(res.statusCode==404){
          reject(res)
          page_show_toast('网络请求失败,请稍后再试',2000)
        }
      },
      fail: function(err) {
        reject(err)
				wx.getNetworkType({
					success: function (res) {
						if(res.networkType=='none'){
							page_show_toast('网络正在路上，请检查您的网络',2000)
						}else{
							page_show_toast('请求超时,请稍后再试',2000)
						}
					}
				})
      }
    })
  })
}
module.exports = {
  formatTime: formatTime,
  formatTime_age: formatTime_age,
  formatTime_year: formatTime_year,
  formatTime_month: formatTime_month,
  formatTime_order: formatTime_order,
  time2date: time2date,
  insertStr: insertStr,
  extend: extend,
  convertToChinaNum: convertToChinaNum,
  randomString: randomString,
  swapArr: swapArr,
  formatTime_year_else: formatTime_year_else,
  formatTime_month_else: formatTime_month_else,
  getweekday: getweekday,
  formatTime_time: formatTime_time,
  removeAllSpace: removeAllSpace,
  show_success_toast: show_success_toast,
  show_fail_toast: show_fail_toast,
  page_show_toast: page_show_toast,
  formatTime_com_time: formatTime_com_time,
  get_distance: get_distance,
  toDecimal: toDecimal,
  toThousands: toThousands,
  downLoadImg: downLoadImg,
  time3date: time3date,
  time4date: time4date,
  baseRequest,
  tokenRequest
}
